package com.gyj.interceptor;

import com.gyj.config.TenantDatasouceConfig;
import com.gyj.feign.UserFeign;
import com.gyj.util.AppContextHelper;
import com.gyj.util.DynamicRoutingDataSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

@Component
public class TenantIntercptor implements HandlerInterceptor {

	@Resource
	private Map<Object, Object> dataSourceMap;

	@Resource
	private DataSourceBuilder dataSourceBuilder;

	@Resource
	private TenantDatasouceConfig tdc;

	@Resource
	private UserFeign userFeign;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			Long tenantId = userFeign.tenantIdByToken(token);
			if (Objects.nonNull(tenantId)) {
				DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) AppContextHelper
						.getBean("dynamicDataSource");
				DataSource dataSource = (DataSource) dataSourceMap.get(tenantId);
				if (Objects.isNull(dataSource)) {
					dataSourceBuilder.url(String.format(
							"jdbc:mysql://%s:%d/%s%d?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true",
							tdc.getHost(), tdc.getPort(), tdc.getSchema(), tenantId));
					dataSourceBuilder.username(tdc.getUsername());
					dataSourceBuilder.password(tdc.getPassword());
					dataSource = dataSourceBuilder.build();
					dataSourceMap.put(tenantId, dataSource);

					dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
					dynamicRoutingDataSource.afterPropertiesSet();
				}
				dynamicRoutingDataSource.setTenantId(tenantId);
				return true;
			} else {
				throw new Exception("请求没有token！");
			}
		}
		return false;
	}

}
